import requests
import json
from datetime import datetime, timedelta

# Zabbix服务器配置
ZABBIX_URL = "http://your_zabbix_server/api_jsonrpc.php"
ZABBIX_USER = "Admin"
ZABBIX_PASSWORD = "zabbix"

# 全局请求头
HEADERS = {"Content-Type": "application/json-rpc"}


def zabbix_api_request(method, params):
    """发送Zabbix API请求"""
    payload = {
        "jsonrpc": "2.0",
        "method": method,
        "params": params,
        "id": 1,
        "auth": None
    }

    # 如果是登录请求则跳过auth
    if method != "user.login":
        payload["auth"] = auth_token

    response = requests.post(
        ZABBIX_URL,
        headers=HEADERS,
        data=json.dumps(payload),
        verify=False  # 如果是HTTPS且使用自签名证书可禁用验证
    )

    if response.status_code != 200:
        raise Exception(f"API请求失败: HTTP {response.status_code}")

    result = response.json()
    if "error" in result:
        raise Exception(f"API错误: {result['error']['data']}")

    return result.get("result", "")


# 1. 获取认证令牌
try:
    auth_token = zabbix_api_request("user.login", {
        "user": ZABBIX_USER,
        "password": ZABBIX_PASSWORD
    })
    print(f"认证成功，Token: {auth_token[:15]}...")
except Exception as e:
    print(f"登录失败: {str(e)}")
    exit(1)

# 2. 获取主机列表
try:
    hosts = zabbix_api_request("host.get", {
        "output": ["hostid", "host"],
        "selectInterfaces": ["ip"],
        "filter": {"status": "0"}  # 只获取启用的主机
    })
    print(f"\n获取到 {len(hosts)} 台主机")
    for host in hosts[:5]:  # 只打印前5台主机示例
        print(f"ID: {host['hostid']}, 主机名: {host['host']}, IP: {host['interfaces'][0]['ip']}")
except Exception as e:
    print(f"获取主机列表失败: {str(e)}")

# 3. 获取指标数据 (CPU利用率)
if hosts:
    try:
        # 获取所有CPU利用率监控项
        cpu_items = zabbix_api_request("item.get", {
            "output": ["itemid", "name", "key_", "hostid"],
            "search": {"key_": "system.cpu.util[,", "name": "CPU utilization"},  # 更精确的搜索
            "hostids": [host["hostid"] for host in hosts],
            "filter": {"value_type": "0", "status": "0"}  # 浮点数类型且启用的监控项
        })

        # 获取最近1小时的指标值
        end_time = datetime.now()
        start_time = end_time - timedelta(hours=1)

        metric_data = {}
        for item in cpu_items:
            try:
                history = zabbix_api_request("history.get", {
                    "output": ["clock", "value"],
                    "itemids": item["itemid"],
                    "history": 0,  # 浮点数历史数据
                    "sortfield": "clock",
                    "sortorder": "DESC",
                    "time_from": int(start_time.timestamp()),
                    "time_till": int(end_time.timestamp()),
                    "limit": 10  # 限制返回数量
                })

                if history:
                    host_name = next((host["host"] for host in hosts if host["hostid"] == item["hostid"]), "Unknown")
                    metric_data[item["itemid"]] = {
                        "host": host_name,
                        "name": item["name"],
                        "key": item["key_"],
                        "values": [{"timestamp": datetime.fromtimestamp(int(h["clock"])), "value": h["value"]} for h in
                                   history]
                    }
            except Exception as e:
                print(f"获取监控项 {item['itemid']} 历史数据失败: {str(e)}")
                continue

        print(f"\n成功获取 {len(metric_data)} 个CPU监控项的历史数据")

        # 打印示例数据
        if metric_data:
            sample_item = next(iter(metric_data.values()))
            print(f"\n示例监控项数据 - 主机: {sample_item['host']}")
            print(f"监控项名称: {sample_item['name']}")
            print(f"最近5个数据点:")
            for point in sample_item["values"][:5]:
                print(f"{point['timestamp']}: {point['value']}%")

    except Exception as e:
        print(f"获取CPU指标数据失败: {str(e)}")

# 4. 获取事件数据 (最近1小时)
try:
    events = zabbix_api_request("event.get", {
        "output": ["eventid", "source", "object", "objectid", "clock", "value", "name"],
        "selectHosts": ["host"],
        "selectRelatedObject": ["description"],  # 获取相关对象信息
        "sortfield": "clock",
        "sortorder": "DESC",
        "time_from": int((datetime.now() - timedelta(hours=1)).timestamp()),
        "limit": 10,
        "filter": {
            "value": "1",  # 只获取问题事件(1表示问题，0表示恢复)
            "source": "0"  # 触发器事件
        }
    })

    print(f"\n获取到 {len(events)} 个事件")

    if events:
        print("\n最近5个事件:")
        for event in events[:5]:
            host_name = event["hosts"][0]["host"] if event.get("hosts") else "Unknown"
            print(f"[{datetime.fromtimestamp(int(event['clock']))}] "
                  f"主机: {host_name} "
                  f"事件ID: {event['eventid']} "
                  f"描述: {event['name']}")

except Exception as e:
    print(f"获取事件数据失败: {str(e)}")

# 5. 登出 (释放会话)
try:
    zabbix_api_request("user.logout", [])
    print("\n已安全登出")
except Exception as e:
    print(f"登出失败: {str(e)}")